/*
 * Copyright @ 2018 河南雪城软件有限公司  All rights reserved.
 *
 */

package com.hw.one.peach.da.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hw.one.client.Client;
import com.hw.one.component.data.transform.excel.Export;
import com.hw.one.core.controller.BaseController;
import com.hw.one.core.logger.annotation.SystemLog;
import com.hw.one.core.logger.constant.LogConstants;
import com.hw.one.core.result.MsgResult;
import com.hw.one.core.service.IDictionaryService;
import com.hw.one.peach.da.service.IPeachDeviceService;
import com.hw.one.unifiedcode.po.UnifiedCodePo;
import com.hw.one.unifiedcode.service.IUnifiedcodeService;

import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 详细描述
 * </p>
 *
 * @author Erick
 * @date 2018/4/17
 */
@RestController
@RequestMapping("particulate")
public class ParticulateController extends BaseController {

	@Resource
	private IPeachDeviceService peachDeviceService;
	
	@Resource
	private IDictionaryService dictionaryService;
	
	@Resource
	private IUnifiedcodeService unifiedcodeService;
	
	// 角标转换
	private final Map<String, String> corner = new HashMap<String, String>(){{
		put("PM2_5", "PM₂.₅");
		put("PM2.5", "PM₂.₅");
		put("PM10", "PM₁₀");
		put("NO2", "NO₂");
		put("O3", "O₃");
		put("O3_8h", "O₃-8h");
		put("Cl", "Cl⁻");

		put("NO3", "NO₃⁻");
		put("SO4", "SO₄²⁻");
		put("SO2", "SO₂");
		put("Na", "Na⁺");
		put("NH4", "NH₄⁺");
		put("K", "K⁺");
		put("Mg", "Mg²⁺");
		put("Ca", "Ca²⁺");
		put("高碳烷烃C6-C12", "高碳烷烃C₆-C₁₂");
		put("高碳烯烃C6-C12", "高碳烯烃C₆-C₁₂");
		put("低碳烷烃C2-C5", "低碳烷烃C₂-C₅");
		put("低碳烯烃C2-C5", "低碳烯烃C₂-C₅");
	}};
	
	private String getFactors(String[] factors) {
		JSONArray dicts = new JSONArray();
		JSONObject mapd = new JSONObject();
		for (String string : factors) {
			mapd = new JSONObject();
			mapd.put("dictCode", string);
			
			if (string.startsWith("inorganic")) {
				mapd.put("catalogCode", "ITP_HM");
			} else if (string.startsWith("water-soluble")) {
				mapd.put("catalogCode", "ITP_IC");
			} else if (string.startsWith("ECOC")) {
				mapd.put("catalogCode", "ITP_OCEC");
			}
			dicts.add(mapd);
		}
		
		Map<String, Object> dictparam = new HashMap<String, Object>();
		dictparam.put("data", dicts);
		List<UnifiedCodePo> results = unifiedcodeService.getCodeInfoList(dictparam);
		
		String factor = "";
		for (int i = 0; i < results.size(); i++) {
			if (i > 0) {
				factor += ",";
			}
			factor += results.get(i).getMyCode();
		}
		
		return factor;
	}
	
	/**
	 * 颗粒物原始数据查询
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "颗粒物原始数据查询", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "颗粒物原始数据查询", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "original-data", method = RequestMethod.GET)
	public MsgResult findAirOriginalData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("颗粒物原始数据查询异常", e);
		}
		return result;
	}
	
	/**
	 * 颗粒物原始数据导出
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "颗粒物原始数据导出", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "颗粒物原始数据导出", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "original-data-export", method = RequestMethod.GET)
	public void exportOriginalData(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> params = wrapParams(request);
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			MsgResult obj = JSON.parseObject(ret, MsgResult.class);
			Gson gson = new Gson();
			JSONObject o = (JSONObject) JSON.toJSON(obj.getData());
			List<Map<String,String>> list = gson.fromJson(o.get("rows").toString(), new TypeToken<List<HashMap<String, String>>>() {}.getType());
			
			Map<String, Object> exceldata = new HashMap<String, Object>();
			exceldata.put("particulate", list);
			Map<String, Object> sheet = new HashMap<String, Object>();
			sheet.put("Sheet1", exceldata);
			
			Export export = new Export();
			String template = "/ext/tpl/excel/da/tpl-particulate-hour-export.xml";
			InputStream xml = this.getClass().getClassLoader().getResourceAsStream(template);
			Workbook workbook = export.exportExcelFromData(xml, sheet);
			
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("颗粒物原始数据.xlsx".getBytes("UTF-8"), "ISO-8859-1"));
			response.setContentType("multipart/form-data");
			
//			OutputStream os = new java.io.FileOutputStream(new File("E:\\颗粒物数据.xlsx"));
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			log.error("颗粒物原始数据查询异常", e);
		}
	}

	/**
	 * 获取无机元素（重金属）的折线图数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取无机元素（重金属）的折线图数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取无机元素（重金属）的折线图数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "hm-thread", method = RequestMethod.GET)
	public MsgResult findHMThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-hm-thread", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取无机元素（重金属）的折线图数据异常", e);
		}
		return result;
	}

	/**
	 * 获取水溶性离子的折线图数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取水溶性离子的折线图数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取水溶性离子的折线图数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "ic-thread", method = RequestMethod.GET)
	public MsgResult findICThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'IC'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-ic-thread", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取水溶性离子的折线图数据异常", e);
		}
		return result;
	}

	/**
	 * 获取有机碳分析的折线图数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取有机碳分析的折线图数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取有机碳分析的折线图数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "ocec-thread", method = RequestMethod.GET)
	public MsgResult findOCECThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-ocec-thread", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取有机碳分析的折线图数据异常", e);
		}
		return result;
	}

	/**
	 * 获取无机元素前十的数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取无机元素前十的数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取无机元素前十的数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "hm-top", method = RequestMethod.GET)
	public MsgResult findHMMaxThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-hm-top", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取无机元素前十的数据异常", e);
		}
		return result;
	}

	/**
	 * 获取水溶性离子的氨氮数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取水溶性离子的氨氮数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取水溶性离子的氨氮数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "sor-nor", method = RequestMethod.GET)
	public MsgResult findICnitrogenThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'IC'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-sor-nor", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取水溶性离子的氨氮数据异常", e);
		}
		return result;
	}

	/**
	 * 获取颗粒物多因子对比的数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "获取颗粒物多因子对比的数据", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "获取颗粒物多因子对比的数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "mult-factor", method = RequestMethod.GET)
	public MsgResult findMultiFactorThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("particulate-mult-factor", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取颗粒物多因子对比的数据异常", e);
		}
		return result;
	}

	/**
	 * 颗粒物相关性分析
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "颗粒物相关性分析", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "颗粒物相关性分析", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "revevance-data", method = RequestMethod.GET)
	public MsgResult findParticulateRelevanceData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			params.remove("monitorCode");
			
			// 转换编码dictcode转为mycode
			params.put("factors", getFactors(String.valueOf(params.get("factors")).split(",")));
			
			Client c = Client.getInstance();
			String ret = c.execute("particulate-revevance-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("颗粒物相关性分析异常", e);
		}
		return result;
	}
	
	/**
	 * 一段时间水溶性粒子数据的均值排序
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "一段时间水溶性粒子数据的均值排序", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "一段时间水溶性粒子数据的均值排序", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "ic-average", method = RequestMethod.GET)
	public MsgResult findICAverageData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			params.remove("monitorCode");
			Client c = Client.getInstance();
			String ret = c.execute("particulate-ic-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("一段时间水溶性粒子数据的均值排序数据异常", e);
		}
		return result;
	}
	
	/**
	 * 颗粒物多因子折线图
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "颗粒物多因子折线图", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "颗粒物多因子折线图", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "factor-thread", method = RequestMethod.GET)
	public MsgResult findMultiPartFactorThreadData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			params.remove("monitorCode");
			
			// 转换编码dictcode转为mycode
			params.put("factors", getFactors(String.valueOf(params.get("factors")).split(",")));
			
			Client c = Client.getInstance();
			String ret = c.execute("particulate-factor-thread", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("颗粒物多因子折线图数据异常", e);
		}
		return result;
	}
	
	/**
	 * 一段时间重金属数据的均值排序
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "一段时间重金属数据的均值排序", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "一段时间重金属数据的均值排序", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "hm-average", method = RequestMethod.GET)
	public MsgResult findHMAverageData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			params.remove("monitorCode");
			Client c = Client.getInstance();
			String ret = c.execute("particulate-hm-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("一段时间重金属数据的均值排序数据异常", e);
		}
		return result;
	}
	
	/**
	 * 一段时间颗粒物数据的均值排序
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "一段时间颗粒物数据的均值排序", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "一段时间颗粒物数据的均值排序", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "factor-average", method = RequestMethod.GET)
	public MsgResult findPartFactorAverageData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'OCEC','IC','HM'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			params.remove("monitorCode");
			Client c = Client.getInstance();
			String ret = c.execute("particulate-factor-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("一段时间颗粒物数据的均值排序数据异常", e);
		}
		return result;
	}
	
	/**
	 * 一段时间颗粒物数据的均值排序
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "颗粒物", notes = "一段时间颗粒物数据的均值排序", httpMethod = "GET")
	@SystemLog(moduleName = "颗粒物", description = "一段时间颗粒物数据的均值排序", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "combo", method = RequestMethod.GET)
	public MsgResult combo(HttpServletRequest request) {
		MsgResult result = null;
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("code", "inorganic");
			List<Map<String, Object>> hm = dictionaryService.retrieveChildListByCode(params);
			params.put("code", "ECOC");
			List<Map<String, Object>> ocec = dictionaryService.retrieveChildListByCode(params);
			params.put("code", "water-soluble");
			List<Map<String, Object>> ic = dictionaryService.retrieveChildListByCode(params);
			
			JSONArray resultArr = new JSONArray();
			JSONObject resultObj = new JSONObject();
			
			JSONObject temp = new JSONObject();
			JSONArray hmarr = new JSONArray();
			for (Map<String, Object> object : hm) {
				temp = new JSONObject();
				temp.put("label", corner.get(object.get("display")) == null ? object.get("display") : corner.get(object.get("display")));
				temp.put("value", object.get("code"));
				temp.put("checked", false);
				hmarr.add(temp);
			}
			resultObj.put("allChecked", false);
			resultObj.put("indeterminate", true);
			resultObj.put("dataType", "无机元素");
			resultObj.put("factor", hmarr);
			resultArr.add(resultObj);
			
			JSONArray ocecarr = new JSONArray();
			for (Map<String, Object> object : ocec) {
				temp = new JSONObject();
				temp.put("label", object.get("display"));
				temp.put("value", object.get("code"));
				temp.put("checked", false);
				ocecarr.add(temp);
			}
			resultObj = new JSONObject();
			resultObj.put("allChecked", false);
			resultObj.put("indeterminate", true);
			resultObj.put("dataType", "ECOC");
			resultObj.put("factor", ocecarr);
			resultArr.add(resultObj);
			
			JSONArray icarr = new JSONArray();
			for (Map<String, Object> object : ic) {
				temp = new JSONObject();
				temp.put("label", object.get("display"));
				temp.put("value", object.get("code"));
				temp.put("checked", false);
				icarr.add(temp);
			}
			resultObj = new JSONObject();
			resultObj.put("allChecked", false);
			resultObj.put("indeterminate", true);
			resultObj.put("dataType", "水溶性离子");
			resultObj.put("factor", icarr);
			resultArr.add(resultObj);
			
			result = MsgResult.okResult(resultArr);
		} catch (Exception e) {
			log.error("一段时间颗粒物数据的均值排序数据异常", e);
			result = MsgResult.errorResult();
		}
		return result;
	}
}
